const jwt = require('jsonwebtoken');
const User = require('../models/User');

const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    const walletAddress = req.header('X-Wallet-Address');

    if (!token && !walletAddress) {
      throw new Error('No authentication provided');
    }

    let user;
    if (token) {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      user = await User.findByPk(decoded.id);
    } else if (walletAddress) {
      user = await User.findOne({ where: { walletAddress } });
    }

    if (!user) {
      throw new Error('User not found');
    }

    req.user = user;
    req.token = token;
    next();
  } catch (error) {
    res.status(401).json({
      status: 'error',
      message: 'Please authenticate'
    });
  }
};

module.exports = auth; 